<template>
  <div class="creation-table-wrapper">
    <el-form :inline="true">
      <el-form-item label="名称">
        <el-input
          size="small"
          placeholder="请输入名称"
          v-model.trim="searchWord"
          clearable
        />
      </el-form-item>
			<el-form-item label="描述">
        <el-input
          size="small"
          placeholder="请输入描述"
          v-model.trim="searchDesc"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          class="el-icon-search"
          size="small"
          @click="getTableByPageAndName()"
          >查询</el-button
        >
        <el-button
          type="default"
          v-show="!props.stable && props.type != 'select'"
          @click="createTableFunc()"
          class="el-icon-plus"
          size="small"
          >创建表</el-button
        >
        <el-button
          type="default"
          v-show="!props.stable && props.type != 'select'"
          @click="syncData()"
          class="el-icon-plus"
          size="small"
          >数据同步</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
			ref="tableRef"
      style="height: calc(100% - 94px); width: 100%"
      :data="tData"
      stripe
      border
      v-loading="tableLoading"
      @selection-change="handleSelectionChange"
    >
			<template #empty>
				<el-empty/>
			</template>
      <el-table-column
                  type="selection"
                  width="40">
                </el-table-column>
      <el-table-column
        prop="table_name"
        label="名称"
        width="200"
        align="center"
      >
        <template #default="scope">
          <el-tag type="primary">{{ scope.row.table_name }}</el-tag>
        </template>
      </el-table-column>
			<el-table-column prop="desc" label="描述" width="150" align="center" show-overflow-tooltip>
			</el-table-column>
			<el-table-column prop="lastTime" v-if="props.type != 'select'" label="最近更新时间" width="160" align="center">
			</el-table-column>
			<el-table-column prop="lastValue" v-if="props.type != 'select'" label="最近更新值" width="100" align="center">
			</el-table-column>
			<!-- <el-table-column prop="type" label="类型" width="100" align="center">
        <template #default="scope">
          <el-tag type="primary">{{ getTableType(scope.row) }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column prop="valueType" label="测点类型" align="center"
        ><template #default="scope">
          <el-tag v-if="scope.row.valueType" type="primary">{{
            scope.row.valueType
          }}</el-tag>
          <el-tag v-else type="primary"> - </el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="props.type != 'select'" prop="operations" label="操作" align="center" fixed="right" width="200">
        <template #default="scope">
          <el-button size="small" @click="btn_queryData(scope.row)">
            查看数据
          </el-button>
          <el-button
            v-show="!props.stable && scope.row.type == 'NORMAL_TABLE'"
            size="small"
            @click="editChildTable(scope.row.table_name)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            v-show="!props.stable"
            @click="clickDeleteButton(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 12px; float: right"
      v-model:current-page="pageInfo.PAGE_NO"
      v-model:page-size="pageInfo.PAGE_SIZE"
      :page-sizes="[10, 20, 50, 100]"
			:pager-count="5"
      background
      :layout="paginationLayout"
      :total="pageInfo.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-drawer
      v-model="dataDrawer"
      class="drawer-dialog"
      :close-on-click-modal="false"
      direction="rtl"
      size="70%"
    >
      <template #header>
        <div>
          <span>数据查询:</span>
          <span class="title">{{ currentTable }}</span>
        </div>
      </template>
      <template #default>
        <div style="height: 100%">
          <data-details
            :dbName="props.dbName"
            :tableName="currentTable"
						:tableType="currentSuperTable"
            :dialogWidth="dialogWidth"
            :height="height"
            :visiable="dataDrawer"
						:dbInfo="props.dbInfo"
						:databaseInfo="props.databaseInfo"
          />
        </div>
      </template>
    </el-drawer>
  </div>

  <el-dialog v-model="dialogVisible" title="数据库配置信息" width="80%" draggable>
            <el-form :inline="true" :model="databaseModel" label-width="150px">
                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="数据库名称">
                            <el-input v-model="databaseModel.name" placeholder="数据库名称"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="数据库ip">
                            <el-input v-model="databaseModel.host" placeholder="数据库ip"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="数据库端口号">
                            <el-input v-model="databaseModel.port" placeholder="数据库端口号"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="数据库用户名">
                            <el-input v-model="databaseModel.username" placeholder="数据库用户名"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="数据库密码">
                            <el-input v-model="databaseModel.password" placeholder="数据库密码"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="目标表名称">
                            <el-input v-model="databaseModel.targetTableName" placeholder="目标表名称"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="开始时间">
                          <el-date-picker v-model="databaseModel.startDatetime" type="datetime" placeholder="选择日期时间">
                          </el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="结束时间">
                          <el-date-picker v-model="databaseModel.endDatetime" type="datetime" placeholder="选择日期时间">
                          </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                    </el-col>
                    <el-col :span="12">
                        <el-button style="float: right;margin-left: 10px;" @click="closeDialog">关闭</el-button>
                        <el-button style="float: right;" type="primary" @click="startSync">开始同步</el-button>
                    </el-col>

                </el-row>
            </el-form>
        </el-dialog>
</template>

<script lang="tsx" setup>
import { defineProps, onMounted, ref, watch } from "vue";
import { getTableByPage, deleteTable } from "@/api/index";
import {syncDataInfo} from '@/api/dataSubscription'
import { ElMessageBox, ElMessage ,ElLoading} from "element-plus";
import DataDetails from "./DataDetails.vue";
const props = defineProps({
  dbName: {
    type: String,
    default: "",
    required: true,
  },
  stable: {
    type: String,
    default: "",
    required: false,
  },
	type:{
		type: String,
    default: "",
    required: false,
	},
  tableType: {
    type: String,
    default: "",
    required: false,
  },
  dialogWidth: {
    type: Number,
    default: 800,
    required: false,
  },
  height: {
    type: Number,
    default: 400,
    required: false,
  },
  visiable: {
    type: Boolean,
    default: false,
    required: false,
  },
	dbInfo:{
		type:Object,
		default:{},
	},
	databaseInfo:{
		type:Array,
		default:[],
	}
});
const searchWord = ref("");
const dialogVisible = ref(false);
const databaseModel = ref({ name: "", isDelete: false, host: "", port: "", username: "", password: "", 
vgroups: 4, buffer: 256,cachesize:1,cachemodel:"last_row",targetTableName:"", startDatetime: null, endDatetime: null });
const multipleSelection  = ref([]);
const spanLength = ref(8);

const searchDesc = ref("");
const tData = ref([]);
const store = {
	info:props.dbInfo,
	databaseInfo: props.databaseInfo,
}
const dataDrawer = ref(false);
const currentTable = ref("");
const currentSuperTable = ref("")
const tableLoading = ref(false);
watch(
  () => props.stable,
  () => {
    getTableByPageAndName();
  }
);
watch(
  () => props.dbName,
  () => {
    initSearchCond();
    getTableByPageAndName();
  },
);
watch(
  () => props.tableType,
  (newval) => {
    if (newval == "table") {
      getTableByPageAndName();
    }
  }
);
watch(
  () => props.visiable,
  (newval) => {
    if (!newval) {
      searchWord.value = "";
    } else {
      initSearchCond();
      getTableByPageAndName();
    }
  }
);

onMounted(() => {
  if (props.stable || props.type == 'select') {
    getTableByPageAndName();
  }
	if(props.type == 'select'){
		paginationLayout.value = 'total, sizes, prev, pager, next'
	}
});

//分页配置
const pageInfo = ref({
  PAGE_NO: 1,
  PAGE_SIZE: 20,
  total: 100,
});
const paginationLayout = ref('total, sizes, prev, pager, next, jumper')
/**
 * 当前页修改
 * @param val 当前页
 */
const handleCurrentChange = (val: number) => {
  pageInfo.value.PAGE_NO = val;
  getTableByPageAndName();
};
/**
 * 每页数据量修改
 * @param val 每页数据量
 */
const handleSizeChange = (val: number) => {
  pageInfo.value.PAGE_SIZE = val;
  getTableByPageAndName();
};
/**
 * 分页获取全部普通表格和子表
 * @param superTableName 超表名称用于查询指定子表
 */
const getTableByPageAndName = () => {
  tableLoading.value = true;
  let data = {
    filterName: searchWord.value,
    dbConfig: {
      ...store.info,
      dbName: props.dbName,
    },
    isSuperTable: false,
    superTableName: props.stable,
    page: {
      ...pageInfo.value,
    },
		likeDesc: searchDesc.value,
		needLastValue:true
  };
	if(props.type == 'select'){
		data.needLastValue = false;
	}
  getTableByPage(JSON.parse(JSON.stringify(data)))
    .then((res: object) => {
      if (res.code == 200 && res.data && res.data.list) {
        //表赋值
        tData.value = res.data.list.map((item: string) => {
          return {
            table_name: item.name,
            // type: item.type,
            valueType: typeConvert(item.supName),
						desc: item.desc && item.desc != 'null' ? item.desc : '-',
						lastTime: item.lastTime ? item.lastTime : '-',
						lastValue: item.lastValue ? item.lastValue : '-'
          };
        });
        pageInfo.value.total = res.data.total;
      } else {
        tData.value = [];
        ElMessage({
          message: "创建表格数据失败",
          type: "error",
        });
      }
      tableLoading.value = false;
    })
    .catch(() => {
      tableLoading.value = false;
    });
};

const typeConvert = (type)=>{
	switch(type){
		case 'tbool':
			return 'BOOL';
		case 'tfloat':
			return 'FLOAT';
		case 'tint':
			return 'INT'
		case 'tdouble':
			return 'DOUBLE'
	}
}

/**
 * 初始化查询条件
 */
const initSearchCond = () => {
  pageInfo.value.PAGE_NO = 1;
  pageInfo.value.PAGE_SIZE = 20;
  searchWord.value = "";
};

const editTable = (table) => {
  // 编辑表的逻辑
  
};

const clickDeleteButton = (rowData) => {
  // 删除表的逻辑
  ElMessageBox.confirm("确认要删除该表格吗？", "删除表格", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let data = {
        dbConfig: {
          ...store.info,
          dbName: props.dbName,
        },
        tableName: rowData.table_name,
      };
      deleteTable(data)
        .then((res) => {
          if (res.code == 200 && res.data) {
            ElMessage({
              type: "success",
              message: "删除成功",
            });
            getTableByPageAndName("");
          } else {
            ElMessage({
              type: "error",
              message: "删除失败：" + res.msg,
            });
          }
        })
        .catch(() => {
          ElMessage({
            type: "error",
            message: "删除失败",
          });
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const btn_queryData = (rowData) => {
  // 数据查询的逻辑
  dataDrawer.value = true;
  let table_name = rowData.table_name;
  currentTable.value = table_name;
	currentSuperTable.value = rowData.valueType;
};

const getTableType = (rowData)=>{
	if(rowData.type == "NORMAL_TABLE"){
		return "普通表"
	}else if(rowData.type == "SYSTEM_TABLE"){
		return "系统表"
	}else if(rowData.type == "CHILD_TABLE"){
		return "子表"
	}else{
		return "-"
	}
}

const emit = defineEmits(["createTableDialogOpen","editChildTable"]);
const createTableFunc = () => {
  emit("createTableDialogOpen", 2);
};

const editChildTable = (tableName)=>{
	emit("editChildTable",tableName)
}

const handleSelectionChange = (val) =>{
  multipleSelection.value = val
}

const syncData = () =>{
  if(props.dbName == null || props.dbName == ''){
      ElMessage({
              message: '请先选择数据库再进行数据同步',
              type: 'error',
            });
      return;
    }
    if(multipleSelection.value.length<=0){
      ElMessage({
              message: '请先选择子表进行同步',
              type: 'error',
            });
      return;
    }
    if(multipleSelection.value.length>1){
      ElMessage({
              message: '请先选择一个子表进行同步',
              type: 'error',
            });
      return;
    }
    databaseModel.value.name = props.dbName;
    databaseModel.value.host = store.info.host;
    databaseModel.value.port = store.info.port;
    databaseModel.value.username = store.info.username;
    databaseModel.value.password = store.info.password;
    dialogVisible.value = true;
};
/**
 * 开始同步
 */
const startSync = () => {
  //初始化超级表需要的参数
  let payload = {
      ...store.info,
      dbName: props.dbName
    };

    let param = {
      dbConfig: payload,
      tDengineConfigDto: databaseModel.value,
      dataList: multipleSelection.value,
    }
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    });
    // dialogVisible.value = false;
    syncDataInfo(param).then(r => {
      loading.close()
      ElMessage({
        message: '结束同步',
        type: 'success',
      });
    }).catch(err => {
      loading.close()
      ElMessage({
        message: '同步失败',
        type: 'error',
      });
    });
}

const closeDialog = () =>{
  dialogVisible.value = false;
};
/**
 * 选中内容
 */
const tableRef = ref(null);
const getTableSelection = ()=>{
	return tableRef.value.getSelectionRows();
}
// 主动暴露childMethod方法
defineExpose({ getTableSelection })
</script>

<style lang="less">
/* 添加一些样式以适应你的需求 */
.creation-table-wrapper {
  height: 100%;
	width: 100%;
  .drawer-dialog {
    .title {
      display: inline-block;
      margin-left: 8px;
    }
  }
  .el-drawer {
    .el-drawer__header {
      align-items: center;
      color: rgb(114, 118, 123);
      display: flex;
      padding: var(--el-drawer-padding-primary);
      margin-bottom: 0;
      padding-bottom: var(--el-drawer-padding-primary);
    }
    .el-drawer__body {
      padding: 12px var(--el-drawer-padding-primary);
    }
  }
}
</style>
